﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace JYH.Framework
{
    public class MarkemImajeSerialPort : SerialPort
    {
        public MarkemImajeSerialPort()
        {
            this.BaudRate = 38400;
            this.PortName = "COM5";

        }
        public MarkemImajeSerialPort(string PortName, int BaudRate)
        {
            this.BaudRate = BaudRate;
            this.PortName = PortName;

        }
        /// <summary>
        /// 发送指令
        /// </summary>
        /// <param name="Command"></param>
        /// <param name="Msg"></param>
        /// <returns></returns>
        public string Send(string Command, out string Msg)
        {
            Msg = string.Empty;
            string response = String.Empty;
            try
            {
                if (!this.IsOpen)
                {
                    this.Open();

                }
                if (this.IsOpen)
                {
                    byte[] message = ConvertHexStrToByteArray(Command);
                    message[message.Length - 1] = BCC_Check_byte(message, 0, message.Length - 1);
                    byte[] reciveData = new byte[0];
                    string cmd = BitConverter.ToString(message, 0, message.Length);
                    cmd = cmd.Replace("-", " ");
                    this.Write(message, 0, message.Length);
                    Thread.Sleep(50);
                    reciveData = new byte[this.BytesToRead];

                    int itemp = this.BytesToRead;
                    int rcvByteLen = 0;

                    for (int i = 0; i < itemp; i++)
                    {
                        reciveData[i] = Convert.ToByte(this.ReadByte());
                        rcvByteLen++;
                    }
                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(Application.StartupPath + @"\Log\Log" + DateTime.Now.ToString("yyyyMMddHH") + ".txt", true))
                    {
                        response = BitConverter.ToString(message, 0, message.Length);
                        response = response.Replace("-", " ");
                        sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + ":" + response);
                    }
                    if (reciveData.Length > 0)
                    {
                        response = BitConverter.ToString(reciveData, 0, reciveData.Length);
                        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(Application.StartupPath + @"\log\Log" + DateTime.Now.ToString("yyyyMMddHH") + ".txt", true))
                        {
                            response = response.Replace("-", " ");
                            sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + ":" + response);

                        }
                    }
                    this.Close();
                    return response;

                }
                else
                {
                    Msg = "Open SerialPort Fail";
                    return response;
                }
            }
            catch (Exception ex)
            {
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(Application.StartupPath + @"\log\Log" + DateTime.Now.ToString("yyyyMMddHH") + ".txt", true))
                {

                    sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + ":" + ex.ToString());


                }
                this.Close();
                return null;
            }
        }
        /// <summary>
        /// 发送OK指令
        /// </summary>
        /// <param name="Command"></param>
        /// <param name="Msg"></param>
        /// <returns></returns>
        public string ReciveOK(out string Msg, string Command = "06")
        {
            Msg = string.Empty;
            string response = String.Empty;
            try
            {
                if (!this.IsOpen)
                {
                    this.Open();

                }
                if (this.IsOpen)
                {
                    byte[] message = ConvertHexStrToByteArray(Command);
                    message[message.Length - 1] = BCC_Check_byte(message, 0, message.Length - 1);
                    byte[] reciveData = new byte[message.Length - 1];
                    string cmd = BitConverter.ToString(message, 0, message.Length);
                    this.Write(message, 0, message.Length);
                    cmd = cmd.Replace("-", " ");
                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(Application.StartupPath + @"\Log\Log" + DateTime.Now.ToString("yyyyMMddHH") + ".txt", true))
                    {
                        response = BitConverter.ToString(message, 0, message.Length);
                        response = response.Replace("-", " ");
                        sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + ":" + response);
                    }
                    //  this.Write(cmd);
                    reciveData = new byte[this.BytesToRead];

                    int itemp = this.BytesToRead;
                    int rcvByteLen = 0;

                    for (int i = 0; i < itemp; i++)
                    {
                        reciveData[i] = Convert.ToByte(this.ReadByte());
                        rcvByteLen++;
                    }
                    //if (reciveData != null)
                    //{
                    //reciveData(new DataReceivedEventArgs(reciveData));
                    //}

                    if (reciveData.Length > 0)
                    {
                        response = BitConverter.ToString(reciveData, 0, reciveData.Length);
                        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(Application.StartupPath + @"\log\Log" + DateTime.Now.ToString("yyyyMMddHH") + ".txt", true))
                        {
                            response = response.Replace("-", " ");
                            sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + ":" + response);

                        }
                    }
                    this.Close();
                    return response;

                }
                else
                {
                    this.Close();
                    Msg = "Open SerialPort Fail";
                    return response;
                }
            }
            catch (Exception ex)
            {
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(Application.StartupPath + @"\log\Log" + DateTime.Now.ToString("yyyyMMddHH") + ".txt", true))
                {

                    sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + ":" + ex.ToString());


                }
                return null;
            }
        }
        /// <summary>
        /// 关墨线
        /// </summary>
        /// <param name="Msg"></param>
        /// <returns></returns>
        public bool JetStop(out string Msg)
        {
            Msg = string.Empty;
            string Rec = string.Empty;
            try
            {

                Rec = Send("C6 00 01 00 01", out Msg);
                if (string.Equals(Rec, "06") || string.Equals(Rec, ""))
                {

                    Msg = "Jet Stop Access!";
                    return true;
                }
                else
                {

                    Msg = "Jet Stop Fail";
                    return false;

                }



            }
            catch (Exception ex)
            {
                Msg = "Jet Stop Fail:" + ex.ToString();
                return false;
            }
        }
        /// <summary>
        /// 开墨线
        /// </summary>
        /// <returns></returns>
        public bool JetStart(out string Msg)
        {
            Msg = string.Empty;
            string Rec = string.Empty;
            try
            {

                Rec = Send("C6 00 01 01 01", out Msg);
                if (string.Equals(Rec, "06") || string.Equals(Rec, ""))
                {

                    Msg = "Jet Start Access!";
                    return true;
                }
                else
                {
                    Msg = "Jet Stop Fail!";
                    return true;
                }



            }
            catch (Exception ex)
            {
                Msg = "Jet Start Fail:" + ex.ToString();
                return false;
            }
        }
        /// <summary>
        /// 机器停机
        /// </summary>
        /// <returns></returns>
        public bool MachineStop(out string Msg)
        {
            Msg = string.Empty;
            string Rec = string.Empty;
            try
            {

                Rec = Send("C6 00 01 08 01", out Msg);
                if (string.Equals(Rec, "06") || string.Equals(Rec, ""))
                {

                    Msg = "Machine Stop Access!";
                    return true;
                }
                else
                {

                    Msg = "Machine Stop Fail!";
                    return true;
                }



            }
            catch (Exception ex)
            {
                Msg = "Machine Stop Fail:" + ex.ToString();
                return false;
            }
        }


        /// <summary>
        /// 机器重启
        /// </summary>
        /// <returns></returns>
        public bool MachineRestart(out string Msg)
        {
            Msg = string.Empty;
            string Rec = string.Empty;
            try
            {

                Rec = Send("C6 00 01 0D 01", out Msg);
                if (string.Equals(Rec, "06") || string.Equals(Rec, ""))
                {

                    Msg = "Machine Start Access!";
                    return true;
                }
                else
                {

                    Msg = "Jet Stop Fail!";
                    return true;
                }



            }
            catch (Exception ex)
            {
                Msg = "Machine Start Fail:" + ex.ToString();
                return false;
            }
        }


        /// <summary>
        /// 机器开机 
        /// </summary>
        /// <returns></returns>
        public bool MachineStart(out string Msg)
        {
            Msg = string.Empty;
            string Rec = string.Empty;
            try
            {

                Rec = Send("C6 00 01 0C 01", out Msg);
                if (string.Equals(Rec, "06") || string.Equals(Rec, ""))
                {

                    Msg = "Machine Stop Access!";
                    return true;
                }
                else
                {
                    Msg = "Machine Stop Fail!";
                    return true;
                }



            }
            catch (Exception ex)
            {
                Msg = "Machine Start Fail:" + ex.ToString();
                return false;
            }
        }


        /// <summary>
        /// 获取打印机报警信息
        /// </summary>
        /// <param name="Msg"></param>
        /// <returns></returns>
        public bool GetALLFaults(out string Msg, out string Faults)
        {
            Msg = string.Empty;
            Faults = string.Empty;
            try
            {

                string Info = Send("DA 00 00 DA", out Msg);

                ReciveOK(out Msg);

                byte[] Result = ConvertHexStrToByteArray(Info.Replace("-", " "));
                if (Result.Length == 1)
                {
                    Msg = "Get Faults Fail";
                    return false;
                }
                else
                {
                    if (Result[1].ToString() == "D2")
                    {
                        int qty = int.Parse(Hex2Ten(BitConverter.ToString(Result, 4, 1)));
                        for (int i = 0; i < qty; i++)
                        {
                            Faults += "FaultCode:" + BitConverter.ToString(Result, 5 + i, 1) + ";";
                        }
                        return true;
                    }
                    else
                    {
                        Msg = "Get Faults Fail";
                        return false;
                    }
                }

            }
            catch (Exception ex)
            {
                Msg = "Machine Start Fail:" + ex.ToString();
                return false;
            }

        }


        public string Ascii2Chr(int asciiCode)

        {

            if (asciiCode >= 0 && asciiCode <= 255)

            {

                System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();

                byte[] byteArray = new byte[] { (byte)asciiCode };

                string strCharacter = asciiEncoding.GetString(byteArray);

                return (strCharacter);

            }

            else

            {

                throw new Exception("ASCII Code is not valid.");

            }

        }

        /// <summary>
        /// 确认报警信息
        /// </summary>
        /// <param name="Msg"></param>
        /// <returns></returns>
        public bool AcknowledgementFaults(out string Msg)
        {

            Msg = string.Empty;
            string Rec = string.Empty;
            try
            {

                Rec = Send("E6 00 00 00", out Msg);

                if (string.Equals(Rec, "06"))
                {

                    Msg = "Acknowledgement Faults Access!";
                    return true;
                }
                else
                {
                    Msg = "Acknowledgement Faults Fail!";
                    return true;
                }
            }
            catch (Exception ex)
            {
                Msg = "Acknowledgement Faults Fail:" + ex.ToString();
                return false;
            }

        }

        /// <summary>
        /// 获取当前打印指令信息
        /// </summary>
        /// <param name="Msg"></param>
        /// <param name="Info">打印指令信息</param>
        /// <param name="OrderNO">打印指令编号 格式（2位长度的16进制字符） 00 01  </param>
        /// <returns></returns>
        public bool GetPrintOrderInfo(string OrderNO, out string Msg, out string Info)
        {
            Msg = string.Empty;
            Info = string.Empty;
            Msg = string.Empty;
            try
            {
                string Commnd = "92 00 02 " + OrderNO + " 00";
                byte[] byteSend = ConvertHexStrToByteArray(Commnd);
                byteSend[byteSend.Length - 1] = BCC_Check_byte(byteSend, 0, byteSend.Length - 1);
                Commnd = BitConverter.ToString(byteSend);
                Commnd = Commnd.Replace("-", " ");
                Commnd = Send(Commnd, out Msg);
                Thread.Sleep(50);
                ReciveOK(out Msg);
                Commnd = Commnd.Replace("-", " ");
                byteSend = ConvertHexStrToByteArray(Commnd);
                if (byteSend[0].ToString() == "15")
                {
                    //this.AcknowledgementFaults(out Msg);
                    Msg = "Get Print Order Fail";
                    return false;
                }
                else
                {
                    if (byteSend.Length > 6)
                    {
                        Info = BitConverter.ToString(byteSend);
                        Info = Info.Replace("-", " ");
                        return true;
                    }
                    else
                    {


                        Msg = "Get Print Order Fail";
                        return false;
                    }
                }





            }
            catch (Exception ex)
            {
                Msg = "获取当前打印指令失败:" + ex.ToString();
                return false;
            }

        }




        /// <summary>
        /// 获取可用的信息储存序号
        /// </summary>
        /// <param name="Msg"></param>
        /// <param name="OrderNO">新指令编号</param>
        /// <returns></returns>
        public bool GetFreeMessageNumber(out string Msg, out string OrderNO)
        {
            OrderNO = string.Empty;
            Msg = string.Empty;
            try
            {


                OrderNO = Send("A2 00 00 A2", out Msg);
                ReciveOK(out Msg);
                OrderNO = OrderNO.Replace("-", " ");
                byte[] byteSend = ConvertHexStrToByteArray(OrderNO);
                if (byteSend[0].ToString() == "15")
                {
                    Msg = "Get Free Message NO Fail";
                    return false;
                }
                else
                {

                    if (byteSend.Length > 6)
                    {
                        string Res = BitConverter.ToString(byteSend, 1, 1);
                        if (!string.Equals(Res, "A3"))
                        {
                            Msg = "Get Print Order Fail";
                            return false;
                        }
                        OrderNO = BitConverter.ToString(byteSend, 4, 2);
                        OrderNO = OrderNO.Replace("-", " ");
                        int decimalValue = Convert.ToInt32(OrderNO.Replace(" ", ""), 16);
                        if (decimalValue > 999)
                        {
                            Msg = "Get Print Order Fail";
                            return false;
                        }
                        return true;
                    }
                    else
                    {


                        Msg = "Get Print Order Fail";
                        return false;
                    }
                }





            }
            catch (Exception ex)
            {
                Msg = "Get Print Order Fail:" + ex.ToString();
                return false;
            }

        }



        /// <summary>
        /// 获取当前正在打印的信息号
        /// </summary>
        /// <param name="Msg"></param>
        /// <param name="Info">当前打印指令编号格式 2位长度的字节 例如 00 01(16进制)</param>
        /// <returns></returns>
        public bool GetActiveMessageNumber(out string Msg, out string Info)
        {
            Msg = string.Empty;
            Info = string.Empty;
            try
            {




                string OrderNO = Send("DB 00 00 DB", out Msg);
                ReciveOK(out Msg);
                if (string.IsNullOrEmpty(OrderNO))
                {
                    Msg = "Get Active Message NO Fail";

                    return false;
                }
                OrderNO = OrderNO.Replace("-", " ");
                byte[] byteSend = ConvertHexStrToByteArray(OrderNO);
                if (byteSend[0].ToString() == "15")
                {
                    Msg = "Get Active Message NO Fail";
                    return false;
                }
                else
                {
                    if (byteSend.Length > 6)
                    {
                        string Res = BitConverter.ToString(byteSend, 1, 1);
                        if (!string.Equals(Res, "91"))
                        {
                            Msg = "Get Active Message NO Fail";
                            return false;
                        }
                        OrderNO = BitConverter.ToString(byteSend, 4, 2);
                        OrderNO = OrderNO.Replace("-", " ");
                        Info = OrderNO;
                        int decimalValue = Convert.ToInt32(OrderNO.Replace(" ", ""), 16);
                        if (decimalValue > 999)
                        {
                            Msg = "Get Active Message NO Fail";
                            return false;
                        }
                        return true;
                    }
                    else
                    {

                        Msg = "Get Active Message NO Fail";
                        return false;
                    }

                }









            }
            catch (Exception ex)
            {

                Msg = "Get Active Message NO Fail:" + ex.ToString();
                return false;
            }

        }



        /// <summary>
        /// 发送打印信息到喷码机
        /// </summary>
        /// <param name="OrderNO">指令编号 10进制转16进制，保留2个</param>
        /// <param name="OrderName">指令名称 转Ascii码后，10进制转16进制 </param>
        /// <param name="MarkingMethod">喷码方式 00 物件 04 间隔 </param>
        /// <param name="FontCode">字体编码 10进制转16进制，保留1个</param>
        /// <param name="StartingPoint">延迟距离 10进制转16进制，保留2个 </param>
        /// <param name="Interval">喷码间距 10进制转16进制，保留2个 </param>
        /// <param name="Speed">喷码速度 10进制转16进制，保留2个 </param>
        /// <param name="Content">喷码内容 转Ascii码后，10进制转16进制</param>
        /// <param name="Msg">反馈信息</param>
        /// <returns></returns>
        public bool SendMessageToPrint(string OrderNO, string OrderName, string MarkingMethod, string FontCode, int StartingPoint, int Interval, int Speed, string Content, out string Msg)
        {
            Msg = string.Empty;
            string Command = "9F";
            try
            {
                if (string.IsNullOrEmpty(OrderName))
                    OrderName = DateTime.Now.ToString("ddHHmm");
                OrderName = StrToHexString(OrderName, 8);
                Content = StrToHexString(Content, 0);

                int CmdLength = ConvertHexStrToByteArray(OrderName).Length + ConvertHexStrToByteArray(Content).Length + 56;
                string Length = IntToHexString(CmdLength, 2);
                Command += " " + Length;

                Command += ' ' + OrderNO;
                //  Command += " 00 01";
                Command += " " + OrderName;
                Command += " C4 00 " + MarkingMethod + " 00 00 01";
                Length = IntToHexString(StartingPoint, 2);
                Command += " " + Length + " 00 03";
                Length = IntToHexString(Interval, 2);
                Command += " " + Length;   //间隔
                Length = IntToHexString(Speed, 2);
                Command += " " + Length + " 00 00"; //速度
                Command += " 89 00 30 30 30 30 30 30 30 30 30 39 39 39 39 39 39 39 39 39 30 31 00 00 00 01";
                Command += " 0A 80 01";
                FontCode = Ten2Hex(FontCode);
                Command += " " + FontCode;
                Command += "  01 10";
                Command += " " + Content + " 10 01 " + FontCode + " 80 01 0D 00";
                byte[] byteSend = ConvertHexStrToByteArray(Command);
                byteSend[byteSend.Length - 1] = BCC_Check_byte(byteSend, 0, byteSend.Length - 1);
                string Info = BitConverter.ToString(byteSend, 0, byteSend.Length);
                Info = Info.Replace("-", " ");
                Info = Send(Info, out Msg);

                ReciveOK(out Msg);
                Info = Info.Replace("-", " ");
                byteSend = ConvertHexStrToByteArray(Info);


                if (byteSend[0].ToString() == "21")
                {
                    Msg = "Send Message To Print Fail";
                    return false;
                }
                else
                {

                    if (byteSend.Length > 2)
                    {

                        string Res = BitConverter.ToString(byteSend, 1, 1);
                        if (!string.Equals(Res, "C5"))
                        {
                            Msg = "Send Message To Print Fail ";
                            return false;
                        }
                        Info = BitConverter.ToString(byteSend, 0, byteSend.Length);
                        Info = Info.Replace("-", " ");

                        return true;
                    }
                    else
                    {


                        Msg = "Send Message To Print Fail";
                        return false;
                    }
                }

            }
            catch (Exception ex)
            {
                Msg = "Send Message To Print Fail:" + ex.ToString();
                return false;
            }
        }

        /// <summary>
        /// 删除打印信息
        /// </summary>
        /// <param name="OrderNO">信息编号</param>
        /// <param name="Msg"></param>
        /// <returns></returns>
        public bool Cancellation(string OrderNO, out string Msg)
        {
            Msg = string.Empty;
            string Rec = string.Empty;
            try
            {

                Rec = Send("C7 00 02 " + OrderNO + " 00", out Msg);
                Thread.Sleep(50);
                ReciveOK(out Msg);
                byte[] byteSend = ConvertHexStrToByteArray(Rec);
                if (byteSend == null)
                {
                    Msg = "Message not cancelled";
                    return false;
                }
                if (byteSend.Length < 6)
                {
                    Msg = "Message not cancelled";
                    return false;
                }
                Rec = BitConverter.ToString(byteSend, 4, 1);
                if (string.Equals(Rec, "06"))
                {
                    Msg = "Message  cancelled";
                    return false;
                }
                else
                {
                    Msg = "Message not cancelled";
                    return false;
                }
            }
            catch (Exception ex)
            {
                Msg = "Select Order Fail:" + ex.ToString();
                return false;
            }
        }

        public bool SelectOrder(string OrderNO, out string Msg)
        {
            Msg = string.Empty;
            string Rec = string.Empty;
            try
            {

                Rec = Send("98 00 02 " + OrderNO + " 00", out Msg);

                if (string.Equals(Rec, "06"))
                {

                    Msg = "Select Order Access!";
                    return true;
                }
                else
                {
                    Msg = "Select Order Fail!";
                    return true;
                }
            }
            catch (Exception ex)
            {
                Msg = "Select Order Fail:" + ex.ToString();
                return false;
            }
        }

        /// <summary>
        /// 获取打印机状态
        /// </summary>
        /// <param name="Msg"></param>
        /// <returns></returns>
        public string GetPrinterStatus(out string Msg)
        {
            Msg = string.Empty;
            string Rec = string.Empty;
            try
            {

                Rec = Send("A6 00 00 A6", out Msg);
                byte[] byteSend = ConvertHexStrToByteArray(Rec);
                ReciveOK(out Msg);
                if (byteSend != null && byteSend.Length > 5)
                {

                    Rec = byteSend[4].ToString();
                }


                if (string.Equals(byteSend[0].ToString(), "6"))
                {

                    Msg = "Select Order Access!";
                    return Rec;
                }
                else
                {
                    Msg = "Select Order Fail!";
                    return Rec;
                }
            }
            catch (Exception ex)
            {
                Msg = "Select Order Fail:" + ex.ToString();
                return Rec;
            }
        }

        /// <summary>
        /// 十进制数值转16进制字符
        /// </summary>
        /// <param name="qty">十进制数值</param>
        /// <param name="Length">16进制字符长度</param>
        /// <returns></returns>
        public string IntToHexString(int qty, int Length)
        {


            byte[] byteArray = BitConverter.GetBytes(qty);
            byte[] bt = new byte[Length];
            if (Length < byteArray.Length)
            {

                for (int i = 0; i < Length; i++)
                {

                    bt[i] = byteArray[i];
                }
            }
            else
            {
                for (int i = 0; i < Length; i++)
                {
                    if (i < byteArray.Length)
                    {
                        bt[i] = byteArray[i];
                    }
                    else
                    {
                        bt[i] = Convert.ToByte(0);
                    }
                }

            }

            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(bt);
            }
            string a = "";


            for (int i = 0; i < bt.Length; i++)

            {

                a += " " + Convert.ToString(bt[i], 16).PadLeft(2, '0').ToUpper();



            }

            return a;

        }


        /// <summary>
        /// 字符转16进制
        /// </summary>
        /// <param name="Str"></param>
        /// <param name="Length"></param>
        /// <returns></returns>
        public string StrToHexString(string Str, int Length)
        {

            if (Str.Length < Length)
            {
                Str = Str.PadRight(Length, ' ');
            }
            byte[] asciiBytes = Encoding.ASCII.GetBytes(Str);
            string a = "";
            for (int i = 0; i < asciiBytes.Length; i++)
            {
                a += " " + Convert.ToString(Ten2Hex(asciiBytes[i].ToString())).ToUpper();

            }


            return a;

        }


        /// <summary>
        /// 从十进制转换到十六进制
        /// </summary>
        /// <param name="ten"></param>
        /// <returns></returns>
        public string Ten2Hex(string ten)
        {
            ulong tenValue = Convert.ToUInt64(ten);
            ulong divValue, resValue;
            string hex = "";
            do
            {
                //divValue = (ulong)Math.Floor(tenValue / 16);

                divValue = (ulong)Math.Floor((decimal)(tenValue / 16));

                resValue = tenValue % 16;
                hex = TenValue2Char(resValue) + hex;
                tenValue = divValue;
            }
            while (tenValue >= 16);
            if (tenValue != 0)
                hex = TenValue2Char(tenValue) + hex;
            return hex;
        }
        /// <summary>
        /// 十进字符制转十六进制字符
        /// </summary>
        /// <param name="ten"></param>
        /// <returns></returns>
        private string TenValue2Char(ulong ten)
        {
            switch (ten)
            {
                case 0:
                case 1:
                case 2:
                case 3:
                case 4:
                case 5:
                case 6:
                case 7:
                case 8:
                case 9:
                    return ten.ToString();
                case 10:
                    return "A";
                case 11:
                    return "B";
                case 12:
                    return "C";
                case 13:
                    return "D";
                case 14:
                    return "E";
                case 15:
                    return "F";
                default:
                    return "";
            }
        }
        /// <summary>
        /// 16进制字符转字节数组
        /// </summary>
        /// <param name="hexStr">16进制字符</param>
        /// <returns></returns>
        public byte[] ConvertHexStrToByteArray(string hexStr)
        {
            hexStr = hexStr.Replace(" ", "").Replace("\n", "");
            string[] array = new string[hexStr.Length / 2];
            byte[] bytes = new byte[array.Length];
            for (int i = 0; i < hexStr.Length; i++)
            {
                array[i / 2] += hexStr[i];
            }
            for (int i = 0; i < array.Length; i++)
            {
                bytes[i] = Convert.ToByte(array[i], 16);
            }
            return bytes;
        }

        /// <summary>
        /// 获取Checksum字符
        /// </summary>
        /// <param name="buffer">字节数组</param>
        /// <param name="start"></param>
        /// <param name="len"></param>
        /// <returns></returns>
        public byte BCC_Check_byte(byte[] buffer, int start = 0, int len = 0)
        {
            if (buffer == null || buffer.Length == 0)
                return 0x00;
            if (start < 0)
                return 0x00;
            if (len == 0)
                len = buffer.Length - start;
            int length = start + len;
            if (length > buffer.Length)
                return 0x00;
            byte bcc = 0; // Initial value
            for (int i = start; i < len; i++)
            {
                bcc ^= buffer[i];
            }
            return bcc;
        }


        /// <summary>
        /// 十六进制转换到十进制
        /// </summary>
        /// <param name="hex"></param>
        /// <returns></returns>
        public string Hex2Ten(string hex)
        {
            int ten = 0;
            for (int i = 0, j = hex.Length - 1; i < hex.Length; i++)
            {
                ten += HexChar2Value(hex.Substring(i, 1)) * ((int)Math.Pow(16, j));
                j--;
            }
            return ten.ToString();
        }

        /// <summary>
        /// 16进制字符转10进制数值
        /// </summary>
        /// <param name="hexChar"></param>
        /// <returns></returns>
        private int HexChar2Value(string hexChar)
        {
            switch (hexChar)
            {
                case "0":
                case "1":
                case "2":
                case "3":
                case "4":
                case "5":
                case "6":
                case "7":
                case "8":
                case "9":
                    return Convert.ToInt32(hexChar);
                case "a":
                case "A":
                    return 10;
                case "b":
                case "B":
                    return 11;
                case "c":
                case "C":
                    return 12;
                case "d":
                case "D":
                    return 13;
                case "e":
                case "E":
                    return 14;
                case "f":
                case "F":
                    return 15;
                default:
                    return 0;
            }
        }


    }
}
